package com.echo.yixiaowu.feature.components

import android.database.ContentObserver
import android.net.Uri
import android.os.Handler
import android.os.Looper
import android.provider.Settings
import androidx.compose.animation.animateColorAsState
import androidx.compose.animation.core.animateDpAsState
import androidx.compose.foundation.background
import androidx.compose.foundation.border
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.IntrinsicSize
import androidx.compose.foundation.layout.PaddingValues
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.aspectRatio
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.layout.width
import androidx.compose.foundation.layout.wrapContentHeight
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.pager.HorizontalPager
import androidx.compose.foundation.pager.PagerState
import androidx.compose.foundation.pager.rememberPagerState
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material3.Button
import androidx.compose.material3.ButtonDefaults
import androidx.compose.material3.HorizontalDivider
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.DisposableEffect
import androidx.compose.runtime.State
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.rememberCoroutineScope
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.vector.ImageVector
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.platform.LocalDensity
import androidx.compose.ui.res.vectorResource
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import androidx.compose.ui.zIndex
import androidx.media3.session.MediaController
import androidx.navigation.NavHostController
import com.echo.yixiaowu.R
import com.echo.yixiaowu.data.model.player.CardDetailItemData
import com.echo.yixiaowu.feature.player.MediaPageIntent
import com.echo.yixiaowu.feature.player.MediaUIState
import com.echo.yixiaowu.feature.player.video.CardDetailComment
import com.echo.yixiaowu.feature.player.video.VideoExpandableDetails
import com.echo.yixiaowu.feature.player.video.VideoFeatureRow
import com.echo.yixiaowu.feature.player.video.VideoSuggestItem
import com.echo.yixiaowu.feature.player.videoPageItem
import com.echo.yixiaowu.layout.XiaowuRow
import com.echo.yixiaowu.util.SystemUtil.getStatusBarTopHeight
import com.echo.yixiaowu.util.SystemUtil.isAutoRotateEnabled
import com.echo.yixiaowu.util.formatTimeString
import java.util.Locale

// 视频播放器
@Composable
fun PortraitVideoPlayerPage(
    navController: NavHostController,
    item: CardDetailItemData.VideoItem,
    resetHideControlTimer: () -> Unit,
    mediaState: MediaUIState,
    mediaController: MediaController?,
    player: @Composable (Modifier) -> Unit,
    onIntent: (MediaPageIntent) -> Unit
) {
    val density = LocalDensity.current
    val pageState: PagerState =
        rememberPagerState(initialPage = 0, pageCount = { videoPageItem.size })

    val aspectRatio = mediaState.width.toFloat() / mediaState.height
    val scope = rememberCoroutineScope()

    val animatedVideoHeight by animateDpAsState(
        targetValue = mediaState.videoHeight
    )

    val videoModifier = Modifier
        .height(animatedVideoHeight)
        .width(animatedVideoHeight * mediaState.width.toFloat() / mediaState.height)

    val videoContainerColor by animateColorAsState(
        targetValue = if (mediaState.isFullScreen) Color.Transparent else Color.Black
    )

    Box(
        modifier = Modifier
            .fillMaxSize()
            .background(Color.Black)
    ) {
        if (mediaController != null) {
            VideoControl(
                modifier = Modifier
                    .fillMaxWidth()
                    .height(IntrinsicSize.Min)
                    .zIndex(99f),
                onToggleFullScreen = {
                    resetHideControlTimer()
                    onIntent(
                        MediaPageIntent.ClickMediaFullScreen(
                            mediaState.isFullScreen, mediaState.originalVideoHeight
                        )
                    )
                },
                bufferProgress = mediaState.bufferProgress,
                progress = mediaState.progress,
                videoDurationString = mediaState.totalDuration.formatTimeString(),
                currentDurationString = mediaState.currentDuration.formatTimeString(),
                totalDuration = mediaState.totalDuration,
                currentDuration = mediaState.currentDuration,
                resetHideControlTimer = resetHideControlTimer,
                isFullScreen = mediaState.isFullScreen,
                isShowControl = mediaState.isShowControl,
                isPlaying = mediaState.isPlaying,
                onShowControls = {
                    resetHideControlTimer()
                    onIntent(MediaPageIntent.ClickShowControls(mediaState.isShowControl))
                },
                onPlayOrPause = {
                    resetHideControlTimer()
                    onIntent(MediaPageIntent.ClickPlaying(mediaState.isPlaying))
                },
                onProgressChange = {
                    resetHideControlTimer()
                    onIntent(MediaPageIntent.SeekToProgress(it))
                },
            ) {
                Box(
                    modifier = Modifier
                        .fillMaxWidth()
                        .wrapContentHeight()
                        .padding(top = getStatusBarTopHeight(density))
                        .background(color = videoContainerColor),
                    contentAlignment = Alignment.Center
                ) {
                    player(videoModifier.aspectRatio(aspectRatio))
                }
            }
        }
        if (!mediaState.isFullScreen) {
            Column(
                modifier = Modifier
                    .fillMaxSize()
                    .padding(top = mediaState.videoHeight + getStatusBarTopHeight(density))
                    .background(Color.White)
            ) {
                XiaowuRow(
                    modifier = Modifier
                        .fillMaxWidth()
                        .height(40.dp)
                        .border(width = 1.dp, color = Color.Gray.copy(0.3f)),
                    titleList = videoPageItem,
                    state = pageState,
                    scope = scope
                )
                HorizontalPager(state = pageState) { page ->
                    run {
                        if (page == 0) {
                            LazyColumn(modifier = Modifier.fillMaxSize()) {
                                item {
                                    UserAvatarComponent(
                                        modifier = Modifier
                                            .fillMaxWidth()
                                            .fillMaxSize()
                                            .padding(start = 16.dp, end = 16.dp, top = 6.dp)
                                    ) {
                                        Button(
                                            onClick = { /*TODO: 关注逻辑*/ },
                                            modifier = Modifier.height(32.dp),
                                            // contentPadding 控制内边距
                                            contentPadding = PaddingValues(
                                                horizontal = 20.dp,
                                                vertical = 2.dp
                                            ),
                                            shape = RoundedCornerShape(18.dp), // 圆角
                                            colors = ButtonDefaults.buttonColors(
                                                containerColor = Color(0xFF42A5F5)
                                            ),
                                            // 设置阴影
                                            elevation = ButtonDefaults.buttonElevation(
                                                defaultElevation = 2.dp
                                            )
                                        ) {
                                            ActionIcon(modifier = Modifier
                                                .size(18.dp)
                                                .padding(end = 2.dp),
                                                imageVector = ImageVector.vectorResource(R.drawable.ic_user_sub),
                                                contentDescription = "点赞",
                                                tint = Color.White,
                                                onClick = {})
                                            Text(
                                                text = "关注",
                                                fontSize = 13.sp,
                                                color = Color.White,
                                            )
                                        }
                                    }
                                }
                                item {
                                    VideoExpandableDetails(
                                        title = "一个普通的视频标题一个普通的视频标题一个普通的视频标题",
                                        playCount = "1.8w",
                                        commentCount = "996",
                                        publishTime = "3天前",
                                        isExpanded = mediaState.isExpanded,
                                        onIsExpanded = {
                                            onIntent(
                                                MediaPageIntent.ClickMediaExpand(
                                                    mediaState.isExpanded
                                                )
                                            )
                                        },
                                        content = "这是视频的详细介绍内容，可以有很多很多文字。\n点击右上角的图标可以展开、收起这部分描述。"
                                    )
                                }
                                item {
                                    // 功能
                                    VideoFeatureRow(
                                        modifier = Modifier.padding(
                                            start = 8.dp, bottom = 12.dp
                                        ),
                                        isFavorite = mediaState.isFavorite,
                                        isLiked = mediaState.isLiked,
                                        isDisliked = mediaState.isDisliked,
                                        onIntent = onIntent
                                    )
                                }
                                // 推荐
                                items(10) { index ->
                                    if (index == 0) HorizontalDivider(
                                        color = Color.Gray.copy(alpha = 0.1f), thickness = 1.dp
                                    )
                                    VideoSuggestItem(title = "996龙国程序员特色工作时长",
                                        author = "996大王",
                                        views = "9.6万",
                                        commentCount = "996",
                                        onMoreClick = {})
                                    HorizontalDivider(
                                        color = Color.Gray.copy(alpha = 0.1f), thickness = 1.dp
                                    )
                                }
                            }
                        } else {
                            CardDetailComment(page)
                        }
                    }
                }
            }
        }
    }
}

@Composable
fun rememberIsAutoRotateEnabled(): State<Boolean> {
    val context = LocalContext.current
    // 使用 mutableStateOf 创建一个可观察的状态，初始值为当前系统设置
    val isAutoRotateEnabled = remember {
        mutableStateOf(isAutoRotateEnabled(context))
    }

    DisposableEffect(Unit) {
        // 创建一个 ContentObserver 来监听设置数据库的变化
        val contentObserver = object : ContentObserver(Handler(Looper.getMainLooper())) {
            override fun onChange(selfChange: Boolean) {
                super.onChange(selfChange)
                isAutoRotateEnabled.value = isAutoRotateEnabled(context)
            }
        }

        // 获取自动旋转设置的 URI
        val settingUri: Uri = Settings.System.getUriFor(Settings.System.ACCELEROMETER_ROTATION)

        // 注册监听器
        context.contentResolver.registerContentObserver(settingUri, false, contentObserver)

        onDispose {
            // 注销监听器
            context.contentResolver.unregisterContentObserver(contentObserver)
        }
    }
    return isAutoRotateEnabled
}

@Composable
fun SeekIndicator(changeText: String, targetText: String) {
    Box(
        modifier = Modifier
            .background(
                Color.Black.copy(alpha = 0.6f),
                shape = RoundedCornerShape(8.dp)
            )
            .padding(horizontal = 16.dp, vertical = 8.dp), contentAlignment = Alignment.Center
    ) {
        Column(horizontalAlignment = Alignment.CenterHorizontally) {
            Text(text = changeText, color = Color.White, fontSize = 24.sp)
            Spacer(modifier = Modifier.height(4.dp))
            Text(text = targetText, color = Color.White, fontSize = 16.sp)
        }
    }
}

fun formatTime(durationMs: Long): String {
    if (durationMs <= 0) return "00:00"
    val totalSeconds = durationMs / 1000
    val seconds = totalSeconds % 60
    val minutes = (totalSeconds / 60) % 60
    val hours = totalSeconds / 3600
    return if (hours > 0) {
        String.format(Locale.getDefault(), "%02d:%02d:%02d", hours, minutes, seconds)
    } else {
        String.format(Locale.getDefault(), "%02d:%02d", minutes, seconds)
    }
}


